import logging

from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone

from account.models import User
from common.models import MusicInfo, Common, CommonSocial
from common.tools.redis_tool import RedisStat
from shop.models import ShopInfo

logger = logging.getLogger('qixiaobao')


class GroupShopping(Common, CommonSocial):
    """
    团长折扣活动表：
        content-eg:
            [component_id, component_id, component_id]
    """
    shop = models.ForeignKey(ShopInfo, verbose_name='店铺', null=True, on_delete=models.SET_NULL)
    title = models.CharField('标题', max_length=255)
    image = models.CharField('图片', max_length=1024, default='1.png')
    desc = models.TextField('活动描述', default='')
    start_time = models.DateTimeField('开始时间')
    end_time = models.DateTimeField('结束时间')
    inventory = models.IntegerField('库存', default=-1, blank=True, help_text='库存数量，-1为库存无限')
    music = models.ForeignKey(MusicInfo, verbose_name='背景音乐', on_delete=models.SET_NULL, null=True, blank=True)
    # video = models.ForeignKey(VideoInfo, verbose_name='主视频', on_delete=models.SET_NULL, null=True, blank=True)
    shelve = models.BooleanField('上架', default=False, help_text='False为下架，True为上架')
    show_group = models.BooleanField('显示团列表', default=False, blank=True)
    BUY_ONCE, BUY_MULT, BUY_NUMBER = 1, 2, 3
    BUY_TYPE = ((BUY_ONCE, '一次'), (BUY_MULT, '多次'), (BUY_NUMBER, '指定次数'))
    buy_type = models.IntegerField('购买设置', choices=BUY_TYPE, default=BUY_ONCE, blank=True)
    auto_refund = models.BooleanField('自动退款', default=False, help_text='true为自动退款，false为手动退款，默认为手动退款')

    def __unicode__(self):
        return '%s-%s' % (self.id, self.title)

    def get_image_url(self):
        return settings.QINIU_DOMAIN + self.image

    def get_models(self):
        return [
            {'number': item.number, 'price': item.price}
            for item in ShoppingModel.objects.filter(info=self, status=ShoppingModel.STATUS_VALID)
        ]

    def has_start(self):
        return self.start_time < timezone.now()

    def has_end(self):
        return self.end_time < timezone.now()

    def get_mobile_url(self):
        return 'http://qxb.dongpouu.com%s?shop=%s' % (reverse('groupshopping:join', args=[self.id]), self.shop_id)

    def get_join_url(self):
        return reverse('order:groupshopping_create_api') + '?shop=%s' % self.shop_id

    def get_pay_url(self):
        return reverse('order:pay_groupshopping') + '?shop=%s' % self.shop_id

    def get_music_url(self):
        if self.music:
            return self.music.get_path_url()
        return ''

    def get_inventory_status(self):
        if self.inventory == -1:
            return True
        return self.inventory > self.sale

    def get_group_list(self):
        return ShoppingGroup.objects.filter(info=self, status=ShoppingGroup.STATUS_VALID)

    class Meta:
        ordering = ['-create_time']
        verbose_name = '团购活动'
        db_table = 'group_shopping'


class ShoppingModel(Common):
    info = models.ForeignKey(GroupShopping, verbose_name='团购信息', related_name='model_groupshopping', null=True,
                             on_delete=models.SET_NULL)
    number = models.IntegerField('团购人数')
    price = models.IntegerField('团购价格')

    def __unicode__(self):
        return '{}-{}-{}'.format(self.id, self.info.title[:4], self.number)

    class Meta:
        unique_together = ['info', 'price', 'number']
        ordering = ['-create_time']
        verbose_name = '团购活动模式'
        db_table = 'group_shopping_model'


class ShoppingGroup(Common):
    """团购小组"""
    info = models.ForeignKey(GroupShopping, verbose_name='团购信息', null=True, on_delete=models.SET_NULL)
    master = models.ForeignKey(User, verbose_name='团长', null=True, blank=True, on_delete=models.SET_NULL)
    number = models.PositiveIntegerField('当前团内人数', default=1)
    # shopping_model持久化到团组，下单时关联
    model_number = models.PositiveIntegerField('当前团所需人数', default=1)
    mdoel_price = models.PositiveIntegerField('当前团价格', default=1)
    left_number = models.PositiveIntegerField('剩余多少人拼团成功', default=1)
    GROUP_DOING, GROUP_SUCCESS, GROUP_FAIL, GROUP_CANCEL = 1, 2, 3, 4
    GROUP_TYPE = ((GROUP_DOING, '团购中'), (GROUP_SUCCESS, '团购成功'),
                  (GROUP_FAIL, '团购失败'), (GROUP_CANCEL, '团购取消'))
    group_state = models.IntegerField('拼团状态', choices=GROUP_TYPE, default=GROUP_DOING, db_index=True)
    type_info = models.CharField('拼团失败对应的原因', max_length=255, null=True, blank=True)

    def __unicode__(self):
        return '%s-%s' % (self.id, self.info.title if self.info else '')

    def get_member_list(self):
        return ShoppingMem.objects.filter(group=self, order__isnull=False, status=ShoppingMem.STATUS_VALID).order_by(
            'role')

    def get_paying_number_key(self):
        return '%s_%s_%s_paying_number' % (self._meta.app_label, self._meta.object_name, self.id)

    def increase_paying_number(self):
        RedisStat().incr(self.get_paying_number_key())

    def decrease_paying_number(self):
        paying_number = int(RedisStat().get(self.get_paying_number_key())) or 0
        RedisStat().set(self.get_paying_number_key(), paying_number - 1 if paying_number and paying_number > 0 else 0)

    def jurge_by_paying_number(self):
        paying_number = int(RedisStat().get(self.get_paying_number_key())) or 0
        logger.debug('shopping_group_paying_number: %s' % paying_number)
        if not paying_number:
            paying_number = 0
            RedisStat().set(self.get_paying_number_key(), 0)
        return paying_number < self.left_number

    def get_group_url(self):
        return 'http://qxb.dongpouu.com%s?shop=%s' % (
            reverse('groupshopping:shopping_group', args=[self.id]), self.info.shop_id)

    def save(self, *args, **kwargs):
        self.left_number = int(self.model_number) - self.number
        if self.left_number == 0:
            self.group_state = self.GROUP_SUCCESS
        return super(ShoppingGroup, self).save(*args, **kwargs)

    class Meta:
        db_table = 'group_shopping_group'
        verbose_name = '团购开团信息'
        ordering = ['-create_time']


class ShoppingMem(Common):
    shop = models.ForeignKey(ShopInfo, verbose_name='店铺', null=True, on_delete=models.SET_NULL)
    info = models.ForeignKey(GroupShopping, verbose_name='团购信息', null=True, on_delete=models.SET_NULL)
    group = models.ForeignKey(ShoppingGroup, verbose_name='开团信息', related_name='mem_group_shopping', null=True,
                              on_delete=models.SET_NULL)
    user = models.ForeignKey(User, verbose_name='参团人员', related_name='group_shoppping_mem_user', null=True,
                             on_delete=models.SET_NULL)
    superior = models.ForeignKey(User, verbose_name=u"来源推客", null=True, blank=True,
                                 related_name='superior_groupshopping_mem', on_delete=models.SET_NULL)
    name = models.CharField('姓名', max_length=100)
    phone = models.CharField('电话号码', max_length=13)
    ROLE_MASTER, ROLE_GROUPER = 1, 2
    ROLE_TYPE = ((ROLE_MASTER, '开团人'), (ROLE_GROUPER, '参团人'))
    role = models.IntegerField('拼团角色', choices=ROLE_TYPE, default=ROLE_GROUPER)
    order = models.ForeignKey('order.Order', verbose_name='订单记录', null=True, blank=True, on_delete=models.SET_NULL)
    refund = models.ForeignKey('order.RefundOrder', verbose_name='退款记录', null=True, blank=True,
                               on_delete=models.SET_NULL)
    CASH_UNUSED, CASH_USED = 1, 2
    CASH_TYPE = ((CASH_UNUSED, '未兑换'), (CASH_USED, '已兑换'))
    cash = models.IntegerField('兑奖状态', choices=CASH_TYPE, default=CASH_UNUSED)
    cash_time = models.DateTimeField('兑奖时间', null=True, blank=True)
    comment = models.CharField('备注', max_length=256, default='', blank=True)

    def __unicode__(self):
        return str(self.id)

    def save(self, *args, **kwargs):
        return super(ShoppingMem, self).save(*args, **kwargs)

    class Meta:
        db_table = 'group_shopping_member'
        verbose_name = '团购参团人员'
        ordering = ['-create_time']
